package com.tczs.client.service;

import com.alibaba.fastjson.JSONObject;
import com.tczs.client.Client;
import com.tczs.client.bean.Command;
import com.tczs.web.config.ConfigData;

import java.util.HashMap;
import java.util.Map;

/**
 * client的创建，获取等操作
 */
public class ClientService {

    //客户端短时间发送大量数据导致粘包,已此字符串进行切割包
    public static final String SPILT_STR = "3LKCJ";
    //requestId 和 result匹配的结果集合
    public static final Map<String,String> RESULT_MAP = new HashMap<>();

    /**
     * 创建一个客户端
     * @param id 登陆用户的id
     * @return
     */
    public static synchronized Client createClient(Long id){
        Client client = Client.LONG_CLIENT_MAP.get(id);
        if(client != null)
            return client;
        client = new Client();
        client.start(ConfigData.getConfigData().getDatabaseIp(),ConfigData.getConfigData().getGetDatabasePort(),id);
        Client.LONG_CLIENT_MAP.put(id,client);
        return client;
    }

    /**
     * 获取一个可用的客户端
     * @param id
     * @return
     */
    public static Client getClient(Long id){
        if(id == null)
            id = -1L;
        Client client = Client.LONG_CLIENT_MAP.get(id);
        if(client == null)
            return createClient(id);
        else
            return client;
    }

    /**
     * 发送命令到服务端并接收返回信息
     * @param id 用户id
     * @param command 发送命令
     * @return 服务端返回的json数据
     */
    public static String send(Long id, Command command) {
        return send(id, (JSONObject) JSONObject.toJSON(command));
    }

    public static String send(Long id,JSONObject jsonObject){
        Client client = getClient(id);
        for(int j=0;j<20;j++){
            if(client.channelId == null) {
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }else
                break;
        }
        String requestId = client.channelId+"-"+client.requestId.getAndIncrement();
        jsonObject.put("requestId",requestId);
        client.send(jsonObject.toJSONString()+SPILT_STR);
        String result = null;
        for(int i=0;i<50;i++){
            result = RESULT_MAP.get(requestId);
            if(result == null) {
                try {
                    Thread.currentThread().sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            else
                break;
        }
        return result;
    }
}
